package com.wlw.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wlw.entity.Admin;
import com.wlw.service.AdminService;

import edu.xjsoft.base.orm.support.PropertyFilter;      
import edu.xjsoft.base.util.CipherUtil;
@Controller
@RequestMapping("/admin/*")
public class AdminAction {
	@Autowired
	private AdminService adminService;
	CipherUtil cipher = new CipherUtil();
	@SuppressWarnings("unused")
	@RequestMapping
	private String login(HttpServletRequest req){
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		System.out.println("加载至此！login。"+uname+","+pwd);
		pwd = cipher.generatePassword(pwd);
		PropertyFilter filters = new PropertyFilter("uname",uname);
		List<Admin> admins = adminService.search(filters);
		if (admins.size()!=0) {
			if (admins.get(0).getPwd().equals(pwd)) {
				req.getSession().setAttribute("admin", admins.get(0));
				return "redirect:../background/index.jsp";		
			}else {
				return "redirect:../background/login.jsp";
			}
		}else {
			return "redirect:../background/login.jsp";
		}
	}
	@RequestMapping("myManage")
	public String myManage(HttpServletRequest req){
		Admin admin = (Admin) req.getSession().getAttribute("admin");
		if (admin==null) {
			return "redirect:../background/login.jsp";
		}else {
			System.out.println("admin:"+admin.getUname());
			return "background/myManage";			
		}
	}
	@RequestMapping("modMy")
	public String modMy(HttpServletRequest req){
		int id = Integer.parseInt(req.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<Admin> admins = adminService.search(filters);
		admins.get(0).setEmail(req.getParameter("email"));
		admins.get(0).setPwd(cipher.generatePassword(req.getParameter("pwd")));
		admins.get(0).setSex(req.getParameter("sex"));
		admins.get(0).setTelPhone(req.getParameter("telPhone"));
		admins.get(0).setUname(req.getParameter("uname"));
		adminService.saveOrUpdate(admins.get(0));
		return "background/success";
	}
	@RequestMapping("logout")
	public String logout(HttpServletRequest req){
		req.getSession().removeAttribute("admin");
		req.getSession().invalidate(); 
		System.out.println("!!!");
		return "redirect:../background/login.jsp";
	}
}
